/*
 * @lc app=leetcode.cn id=1 lang=javascript
 *
 * [1] 两数之和
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  return method2(nums,target);
};
//console.log(twoSum([2,3],5))
/**
 * Your runtime beats 84.59 % of javascript submissions
 * Your memory usage beats 55.38 % of javascript submissions (41.6 MB)
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]} 
 */
function method2(nums, target) {
  let obj = {};
  for(let i=0;i<nums.length;i++){
    let num = nums[i];
    let n = target - num;
    if(num in obj) {
      return [i,obj[num]];
    }else{
      obj[n] = i;
    }
  }
}

/**
 * Your runtime beats 55.99 % of javascript submissions
 * Your memory usage beats 10.9 % of javascript submissions (43.3 MB)
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
function method1(nums, target) {
  //存放nums数组中元素和下标的映射方便计算
  let map = {};
  let ele = null;
  let other = null;
  let n = null;
  let idxArray = null;
  for(let i=0;i<nums.length;i++){
    ele = nums[i];
    //下标缓存使用数组防止nums中有重复的元素
    if(map[ele]) {
      map[ele].push(i);
    }else{
      //{3=[0,1]}如果第一和第二个元素出现两个3
      map[ele] = [i];
    }
    other = target-ele;
    idxArray = map[other];
    if(idxArray && idxArray.length>=1) {
      //从下标缓存取出比i小的一个元素
      n = idxArray.filter(e=>e<i);
      if(n.length>0) {
        return [n[0],i]
      }
    }   
  }
}
// @lc code=end

